package com.situ.company.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.situ.company.dao.IUserRoleDao;
import com.situ.company.util.JDBCUtil;

public class UserRoleDaoImpl implements IUserRoleDao {

	@Override
	public int insert(int userId, int roleId) {
		Connection connection = null;
		PreparedStatement statement = null;
		int count = 0;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "insert into user_role(user_id,role_id) values(?,?)";
			statement = connection.prepareStatement(sql);
			statement.setInt(1, userId);
			statement.setInt(2, roleId);
			System.out.println(statement);
			statement.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return count;
	}

	@Override
	public List<Integer> selectRoleIdByUserId(int id) {
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		List<Integer> list = new ArrayList<Integer>();
		try {
			connection = JDBCUtil.getConnection();
			String sql = "select role_id from user_role where user_id=?";
			statement = connection.prepareStatement(sql);
			statement.setInt(1, id);
			resultSet = statement.executeQuery();
			while (resultSet.next()) {
				int roleId = resultSet.getInt("role_id");
				list.add(roleId);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public void deleteByUserId(Integer id) {
		Connection connection = null;
		PreparedStatement statement = null;
		int count = 0;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "delete from user_role where user_id=?";
			statement = connection.prepareStatement(sql);
			statement.setInt(1, id);
			System.out.println(statement);
			count = statement.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

}
